<template>
  <view class="container">
    <!--顶部返回按钮-->
    <text class="back-btn iconfont iconzuojiantou-up" @tap="navBack"></text>
    <!--插画-->
    <view class="right-top-sign"></view>
    <!-- 设置白色背景防止软键盘把下部绝对定位元素顶上来盖住输入框等 -->
    <view class="wrapper">
      <view class="welcome">
        欢迎回来！
      </view>
      <view class="input-content">
        <view class="input-item">
          <text class="tit">手机号码</text>
          <input
              type="number"
              name="mobile"
              v-model="loginParams.mobile"
              placeholder="请输入手机号码"
              maxlength="11"
              @blur="blurMobileChange"
          />
        </view>
        <view class="input-item" v-if="loginByPass">
          <text class="tit">密码</text>
          <input
              name="password"
              type="password"
              v-model="loginParams.password"
              placeholder="请输入密码"
              maxlength="20"
          />
        </view>

        <view class="input-item input-item-sms-code" v-if="!loginByPass">
          <view class="input-wrapper">
            <view class="rf-input-wrapper">
              <view class="tit">验证码</view>
              <input
                  type="number"
                  v-model="loginParams.code"
                  placeholder="请输入验证码"
                  maxlength="4"
                  data-key="mobile"
              />
            </view>
            <button class="sms-code-btn" :loading="btnLoading" :disabled="smsCodeBtnDisabled" @tap.stop="getSmsCode">
              <text v-if="!smsCodeBtnDisabled">获取验证码</text>
              <text v-else class="sms-code-resend">{{ `重新发送 (${codeSeconds})` }}</text>
            </button>

          </view>
        </view>
        <button class="confirm-btn" :disabled="btnLoading" :loading="btnLoading" @tap="toLogin">登录</button>
      </view>
      <view @tap="showLoginBySmsCode" class="forget-section">
        {{ loginByPass ? "验证码登录" : "密码登录" }}
      </view>
      <view class="forget-section" @tap="goto('/pages/public/password')">
        忘记密码?
      </view>
    </view>
    <view class="register-section">
      还没有账号?
      <text @tap="goto('/pages/public/register')">马上注册</text>
      或者
      <text @tap="goto('/pages/index/index')">返回主页</text>
    </view>
  </view>
</template>

<script>
	import moment from '@/utils/moment';
	import {Public} from '@/model/public.js';
	var publicModel = new Public();
	export default {
		data() {
			return {
				loginParams: {
				  mobile: '',
						  code: '',
				  password: ''
				},
				btnLoading: false,
				reqBody: {},
				codeSeconds: 0, // 验证码发送时间间隔
				loginByPass: true,
				smsCodeBtnDisabled: true,
				userInfo: null,
				sendCodeTime:60
			}
		},
		onLoad() {
			const time = moment().valueOf() / 1000 - uni.getStorageSync('loginSmsCodeTime');
			if (time < 60) {
				this.codeSeconds = this.$data.sendCodeTime - parseInt(time, 10);
				this.handleSmsCodeTime(this.codeSeconds);
			} else {
				this.codeSeconds = this.$data.sendCodeTime;
				this.smsCodeBtnDisabled = false;
				uni.removeStorageSync('loginSmsCodeTime')
			}
			this.userInfo = uni.getStorageSync('userInfo');
		},
		methods: {
			loginTest(mobile, password) {
				this.loginParams.mobile = mobile;
				this.loginParams.password = password;
			},
			// 发送验证码并进入倒计时
			async getSmsCode() {
				this.reqBody['mobile'] = this.loginParams['mobile'];
				let checkSendCode = this.$mGraceChecker.check(this.reqBody, this.$mFormRule.sendCodeRule);
				if (!checkSendCode) {
					this.$mHelper.toast(this.$mGraceChecker.error);
					return;
				}
				var param = {
					mobile: this.loginParams.mobile,
					usage: 'login'
				}
				publicModel.smsSend(param,(data) => {
					this.$mHelper.toast("测试时验证码为：1234");
					this.smsCodeBtnDisabled = true;
					uni.setStorageSync('loginSmsCodeTime', moment().valueOf() / 1000);
					this.handleSmsCodeTime(59);
				});
			},
			handleSmsCodeTime (time) {
					let timer = setInterval(() => {
						if (time === 0) {
							clearInterval(timer);
							this.smsCodeBtnDisabled = false;
						} else {
							this.codeSeconds = time;
							this.smsCodeBtnDisabled = true;
							time--
						}
					}, 1000);
			},
			// 失去焦点的手机号
			blurMobileChange(e) {
				this.mobile = e.detail.value
			},
			// 切换登录方式
			showLoginBySmsCode() {
				this.loginByPass = !this.loginByPass;
			},
			// 提交表单
			async toLogin() {
				this.reqBody['mobile'] = this.loginParams['mobile'];
				let cheRes, loginApi;
				if (this.loginByPass) {
					this.reqBody['url'] = "site/login";
					this.reqBody['password'] = this.loginParams['password'];
					cheRes = this.$mGraceChecker.check(this.reqBody, this.$mFormRule.loginByPassRule);
				} else {
					this.reqBody['code'] = this.loginParams['code'];
					this.reqBody['url'] = "site/mobile-login";
					cheRes = this.$mGraceChecker.check(this.reqBody, this.$mFormRule.loginByCodeRule);
				}
				if (!cheRes) {
					uni.showToast({
						icon:'none',
						title:this.$mGraceChecker.error
					})
					return;
				}
				/*  #ifdef  APP-PLUS  */
				this.reqBody.group = 'jhxEduApp'
				/*  #endif  */
				/*  #ifdef H5  */
				this.reqBody.group = 'jhxEduH5'
				/*  #endif  */
				/*  #ifdef  MP-WEIXIN  */
				this.reqBody.group = 'jhxEduWechatMq'
				/*  #endif  */
				/*  #ifdef  MP-QQ  */
				this.reqBody.group = 'jhxEduQqMq'
				/*  #endif  */
				this.handleLogin(this.reqBody)
			},
			// 登录
			async handleLogin(params) {
				this.btnLoading = true;
				publicModel.login(params,(res) => {
					this.btnLoading = false;
					if(res.code != '200' || res.code != 200){
						return false;
					}
					const userInfo = res.data.member;
					//保存token信息
					uni.setStorageSync('accessToken', res.data.access_token);
					uni.setStorageSync('refreshToken', res.data.refresh_token);
					uni.setStorageSync('userInfo', userInfo);
					//绑定
					console.log(this.userInfo);
					if (this.userInfo && (this.userInfo.openid || this.userInfo.openId)) {
						const oauthClientParams = {}
						/*  #ifdef MP-WEIXIN */
						oauthClientParams.oauth_client = 'wechatMp';
						/*  #endif  */
						/*  #ifndef MP-WEIXIN */
						oauthClientParams.oauth_client = 'wechat';
						/*  #endif  */
						const userInfo = JSON.parse(this.userInfo);
						this.$http.post(authLogin, {
							...userInfo,
							...oauthClientParams,
							gender: userInfo.sex || userInfo.gender,
							oauth_client_user_id: userInfo.openid || userInfo.openId,
							head_portrait: userInfo.headimgurl || userInfo.avatarUrl
						});
					}
					
					const backToPage = uni.getStorageSync('backToPage');
					if (backToPage) {
						var route = JSON.parse(backToPage);
						var url = this.createUrl(route.route,route.query);
						uni.removeStorageSync('backToPage');
						uni.removeStorageSync('wechatUserInfo');
						this.goto(url);
						return;
					} else {
						uni.switchTab({
							url:'/pages/user/user'
						})
					}
				})
			}
		}
	}
</script>

<style lang='scss'>
  page {
    background: #fff;
  }

  .container {
    padding-top: 115px;
    position: relative;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    background: #fff;
  }

  .wrapper {
    position: relative;
    z-index: 90;
    background: #fff;
    padding-bottom: 40upx;
  }

  .back-btn {
    position: absolute;
    left: 40upx;
    z-index: 9999;
    padding-top: var(--status-bar-height);
    top: 40upx;
    font-size: 40upx;
  }

  .left-top-sign {
    font-size: 120upx;
    position: relative;
    left: -16upx;
  }

  .right-top-sign {
    position: absolute;
    top: 80upx;
    right: -30upx;
    z-index: 95;

    &:before, &:after {
      display: block;
      content: "";
      width: 400upx;
      height: 80upx;
      background: #b4f3e2;
    }

    &:before {
      transform: rotate(50deg);
      border-radius: 0 50px 0 0;
    }

    &:after {
      position: absolute;
      right: -198upx;
      top: 0;
      transform: rotate(-50deg);
      border-radius: 50px 0 0 0;
      /* background: pink; */
    }
  }

  .left-bottom-sign {
    position: absolute;
    left: -270upx;
    bottom: -320upx;
    border: 100upx solid #d0d1fd;
    border-radius: 50%;
    padding: 180upx;
  }

  .welcome {
    position: relative;
    left: 50upx;
    top: -90upx;
    font-size: 46upx;
    color: #555;
    text-shadow: 1px 0px 1px rgba(0, 0, 0, .3);
  }

  .input-content {
    padding: 0 60upx;
  }

  .input-item {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    padding: 0 30upx;
    height: 120upx;
    border-radius: 4px;
    margin-bottom: 50upx;
	border-bottom: 1px solid $uni-border-color;
    &:last-child {
      margin-bottom: 0;
    }

    .tit {
      height: 50upx;
      line-height: 56upx;
    }

    input {
      height: 60upx;
      width: 100%;
    }
  }

  .input-item-sms-code {
    position: relative;
		width: 100%;
    .sms-code-btn {
      position: absolute;
      color: #111;
      right: 20upx;
      bottom: 20upx;
      font-size: 28upx;
    }

    .sms-code-resend {
      color: #999;
    }

    .sms-code-btn:after {
      border: none;
      background-color: transparent;
    }
  }

  .forget-section {
    text-align: center;
    margin-top: 40upx;
  }

  .register-section {
    margin: 30upx 0 50upx 0;
    width: 100%;
    text-align: center;

    text {
      margin-left: 10upx;
    }

    text:first-child {
      margin-right: 10upx;
    }
  }

  .btn-group {
    display: flex;
    margin-bottom: 20upx;
  }
</style>
